﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Ducu.UI.Responsible.WebHelper
{
    public class PrepageUrlHelper
    {
        public HttpContextBase Context { get; set; }
        public PrepageUrlHelper(HttpContextBase context)
        {
            Context = context;
        }


        /// <summary>
        /// get the prepage to use it as url parameter
        /// </summary>
        /// <returns>if there has been one prepage parameter in the url, use the url from url parameter
        /// else use the current url</returns>
        public string Get()
        {
            //check if there has been prepage first
            //only when there is no prepage, then use current url as prepage
            if (string.IsNullOrEmpty(GetFromUrl()))
            {
                return Context.Server.UrlEncode(getCurrentUrl());
            }
            else
            {
                return Context.Server.UrlEncode(GetFromUrl());
            }
        }

        /// <summary>
        /// redirect the prepage:
        /// if there is no prepage in the url, to default url;
        /// else to the prepage from url
        /// </summary>
        public RedirectResult Return(string defaultUrl)
        {
            if (!string.IsNullOrEmpty(GetFromUrl()))
            {
                return new RedirectResult(GetFromUrl());
            }
            else
            {
                return new RedirectResult(defaultUrl);
            }
        }

        /// <summary>
        /// redirect to the home page when there is no prepage in the url
        /// </summary>
        public RedirectResult Return()
        {
            return Return(@"/");
        }

        private string getCurrentUrl()
        {
            return Context.Request.Url.PathAndQuery;
        }

        /// <summary>
        /// get prepage from url parameter
        /// </summary>
        /// <returns>can be string.empty if no such url parameter</returns>
        public string GetFromUrl()
        {
            //why this is still necessary? why not get it from Action's parameter?
            //because it's still used by ChildAction, etc
            return Context.Request.QueryString["prepage"];
        }

        /// <summary>
        /// get the url when refusing the access
        /// </summary>
        /// <returns></returns>
        public string GetRefuseAccess()
        {
            //TODO: can show detailed/different reminder by add enum for "refuse"
            string wantAccess = Context.Server.UrlEncode(Context.Request.Url.PathAndQuery);
            return @"/Log/On?refuse=1&prepage=" + wantAccess;
        }
    }
}